/**
 * 中华非遗官方网站主要JavaScript功能
 * 包含导航交互、页面动画和用户体验优化
 * AI对话功能由ai-chat-final.js独立处理
 */

// 文档加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能模块
    initNavigation();
    initScrollEffects();
    initAnimations();
    initPageLoading();
    
    // 首页特殊动画初始化
    if (document.getElementById('heroSection')) {
        initHomepageAnimation();
    }

    // 认识非遗页面特有功能
    if (document.body.classList.contains('theme-about')) {
        initHeritageSearch();
        initSuggestions();
        initKnowledgeCards();
    }
});

/**
 * 初始化导航功能
 * 包含移动端菜单切换和活动状态管理
 */
function initNavigation() {
    const hamburger = document.getElementById('hamburger');
    const navMenu = document.getElementById('navMenu');
    const navLinks = document.querySelectorAll('.nav-link');
    
    // 移动端菜单切换功能
    if (hamburger && navMenu) {
        hamburger.addEventListener('click', function() {
            navMenu.classList.toggle('active');
            hamburger.classList.toggle('active');
            
            // 动画效果：汉堡菜单图标变化
            const spans = hamburger.querySelectorAll('span');
            spans.forEach((span, index) => {
                if (hamburger.classList.contains('active')) {
                    if (index === 0) span.style.transform = 'rotate(45deg) translate(5px, 5px)';
                    if (index === 1) span.style.opacity = '0';
                    if (index === 2) span.style.transform = 'rotate(-45deg) translate(7px, -6px)';
                } else {
                    span.style.transform = 'none';
                    span.style.opacity = '1';
                }
            });
        });
    }
    
    // 导航链接点击处理
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            // 移除所有活动状态
            navLinks.forEach(nav => nav.classList.remove('active'));
            // 添加当前活动状态
            this.classList.add('active');
            
            // 移动端：点击链接后关闭菜单
            if (window.innerWidth <= 768) {
                navMenu.classList.remove('active');
                hamburger.classList.remove('active');
                
                // 重置汉堡菜单图标
                const spans = hamburger.querySelectorAll('span');
                spans.forEach(span => {
                    span.style.transform = 'none';
                    span.style.opacity = '1';
                });
            }
        });
    });
    
    // 窗口大小变化时的处理
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768) {
            navMenu.classList.remove('active');
            hamburger.classList.remove('active');
            
            // 重置汉堡菜单图标
            const spans = hamburger.querySelectorAll('span');
            spans.forEach(span => {
                span.style.transform = 'none';
                span.style.opacity = '1';
            });
        }
    });
}

/**
 * 初始化滚动效果
 * 包含导航栏透明度变化和元素出现动画
 */
function initScrollEffects() {
    const header = document.querySelector('.main-header');
    let lastScrollTop = 0;
    
    window.addEventListener('scroll', function() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        
        // 导航栏滚动效果 - 使用CSS类来控制样式变化
        if (header) {
            if (scrollTop > 50) {
                header.classList.add('scrolled');
            } else {
                header.classList.remove('scrolled');
            }
        }
        
        // 元素滚动进入视图动画
        animateOnScroll();
        
        lastScrollTop = scrollTop;
    });
}

/**
 * 滚动进入视图动画
 * 为页面元素添加淡入效果
 */
function animateOnScroll() {
    const elements = document.querySelectorAll('.feature-card, .news-card');
    
    elements.forEach(element => {
        const elementTop = element.getBoundingClientRect().top;
        const elementVisible = 150;
        
        if (elementTop < window.innerHeight - elementVisible) {
            element.classList.add('fade-in');
        }
    });
}

/**
 * 初始化页面动画
 * 为页面加载添加动画效果
 */
function initAnimations() {
    // 英雄区块动画
    const heroContent = document.querySelector('.hero-content');
    if (heroContent) {
        setTimeout(() => {
            heroContent.style.opacity = '1';
            heroContent.style.transform = 'translateY(0)';
        }, 300);
    }
    
    // 特色卡片悬浮效果增强
    const featureCards = document.querySelectorAll('.feature-card');
    featureCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-12px) scale(1.02)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });
    
    // 新闻卡片动画效果
    const newsCards = document.querySelectorAll('.news-card');
    newsCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-8px)';
            this.style.boxShadow = '0 8px 32px rgba(0,0,0,0.2)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
        });
    });
}

/**
 * 初始化页面加载效果
 * 页面加载完成后的优化处理
 */
function initPageLoading() {
    // 页面加载完成后移除loading状态
    window.addEventListener('load', function() {
        document.body.classList.add('loaded');
        
        // 导航栏加载完成后移除动画
        setTimeout(() => {
            const navMenu = document.querySelector('.nav-menu');
            if (navMenu) {
                navMenu.classList.add('loaded');
            }
        }, 500);
    });
}

/**
 * 首页动画初始化
 * 实现广东非遗元素图到三缠绕图标的动画转换
 */
function initHomepageAnimation() {
    const heritageImage = document.getElementById('heritageImage');
    const interactiveContent = document.getElementById('interactiveContent');
    const circles = document.querySelectorAll('.circle');
    
    // 确保初始状态正确
    if (heritageImage) {
        heritageImage.classList.remove('blurred');
    }
    if (interactiveContent) {
        interactiveContent.classList.remove('active');
    }
    
    // 1秒后开始转换动画
    setTimeout(() => {
        // 第一阶段：广东非遗元素图变模糊成为背景
        if (heritageImage) {
            heritageImage.classList.add('blurred');
        }
        
        // 第二阶段：0.8秒后显示三缠绕图标和标语
        setTimeout(() => {
            if (interactiveContent) {
                interactiveContent.classList.add('active');
            }
        }, 800);
        
    }, 1000);
    
    // 为三个圆添加点击事件
    circles.forEach(circle => {
        circle.addEventListener('click', function() {
            const theme = this.getAttribute('data-theme');
            
            // 添加点击动画
            this.style.transform = 'scale(0.95) translateY(-5px)';
            setTimeout(() => {
                this.style.transform = '';
            }, 150);
            
            // 延迟后跳转页面
            setTimeout(() => {
                switch(theme) {
                    case 'about':
                        window.location.href = 'about.html';
                        break;
                    case 'explore':
                        window.location.href = 'explore.html';
                        break;
                    case 'heritage':
                        window.location.href = 'heritage.html';
                        break;
                }
            }, 300);
        });
        
        // 添加悬浮时的标语高亮效果
        circle.addEventListener('mouseenter', function() {
            const theme = this.getAttribute('data-theme');
            const slogan = document.querySelector(`.slogan-${theme}`);
            if (slogan) {
                slogan.style.transform = 'scale(1.05)';
                slogan.style.boxShadow = '0 15px 40px rgba(0, 0, 0, 0.2)';
            }
        });
        
        circle.addEventListener('mouseleave', function() {
            const theme = this.getAttribute('data-theme');
            const slogan = document.querySelector(`.slogan-${theme}`);
            if (slogan) {
                slogan.style.transform = 'scale(1)';
                slogan.style.boxShadow = '';
            }
        });
    });
    
    // 添加标语点击事件
    const slogans = document.querySelectorAll('.slogan-content');
    slogans.forEach(slogan => {
        slogan.addEventListener('click', function() {
            const parentSlogan = this.closest('.slogan');
            let targetPage = '';
            
            if (parentSlogan.classList.contains('slogan-about')) {
                targetPage = 'about.html';
            } else if (parentSlogan.classList.contains('slogan-explore')) {
                targetPage = 'explore.html';
            } else if (parentSlogan.classList.contains('slogan-heritage')) {
                targetPage = 'heritage.html';
            }
            
            if (targetPage) {
                window.location.href = targetPage;
            }
        });
        
        // 添加鼠标悬浮样式
        slogan.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px) scale(1.02)';
            this.style.cursor = 'pointer';
        });
        
        slogan.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });
}

/**
 * 重置首页动画
 * 用于页面重新加载或需要重置动画状态时
 */
function resetHomepageAnimation() {
    const heritageImage = document.getElementById('heritageImage');
    const interactiveContent = document.getElementById('interactiveContent');
    
    if (heritageImage) {
        heritageImage.classList.remove('blurred');
    }
    
    if (interactiveContent) {
        interactiveContent.classList.remove('active');
    }
}

/**
 * 初始化搜索功能
 */
function initHeritageSearch() {
    const searchInput = document.getElementById('heritageSearch');
    const searchBtn = document.querySelector('.search-btn');
    
    if (!searchInput || !searchBtn) return;

    // 实时搜索
    let searchTimeout;
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            const query = this.value.trim();
            if (query.length > 0) {
                performSearch(query);
            } else {
                hideSearchResults();
            }
        }, 300);
    });

    // 搜索按钮点击
    searchBtn.addEventListener('click', function() {
        const query = searchInput.value.trim();
        if (query) {
            performSearch(query);
        }
    });

    // 回车键搜索
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            const query = this.value.trim();
            if (query) {
                performSearch(query);
            }
        }
    });
}

/**
 * 执行搜索
 * @param {string} query - 搜索关键词
 */
function performSearch(query) {
    console.log('搜索关键词:', query);
    
    const allCards = document.querySelectorAll('.heritage-card');
    const categorySections = document.querySelectorAll('.category-section');
    const searchResults = document.getElementById('searchResults');
    const resultsContainer = document.getElementById('resultsContainer');
    const noResults = document.getElementById('noResults');
    
    if (!searchResults || !resultsContainer || !noResults) return;

    // 清空搜索结果
    resultsContainer.innerHTML = '';
    
    // 搜索匹配的卡片
    const matchedCards = [];
    allCards.forEach(card => {
        const keywords = card.getAttribute('data-keywords') || '';
        const title = card.querySelector('h4')?.textContent || '';
        const description = card.querySelector('p')?.textContent || '';
        const tags = Array.from(card.querySelectorAll('.tag')).map(tag => tag.textContent).join(' ');
        
        const searchText = `${keywords} ${title} ${description} ${tags}`.toLowerCase();
        
        if (searchText.includes(query.toLowerCase())) {
            matchedCards.push(card.cloneNode(true));
        }
    });

    // 显示搜索结果
    if (matchedCards.length > 0) {
        matchedCards.forEach(card => {
            addCardClickEffect(card);
            resultsContainer.appendChild(card);
        });
        noResults.style.display = 'none';
        
        // 隐藏分类区域
        categorySections.forEach(section => {
            section.style.display = 'none';
        });
    } else {
        noResults.style.display = 'block';
        categorySections.forEach(section => {
            section.style.display = 'none';
        });
    }
    
    searchResults.style.display = 'block';
}

/**
 * 隐藏搜索结果
 */
function hideSearchResults() {
    const searchResults = document.getElementById('searchResults');
    const categorySections = document.querySelectorAll('.category-section');
    
    if (searchResults) {
        searchResults.style.display = 'none';
    }
    
    // 重新显示分类区域
    categorySections.forEach(section => {
        section.style.display = 'block';
    });
}

/**
 * 初始化搜索建议
 */
function initSuggestions() {
    const searchInput = document.getElementById('heritageSearch');
    if (!searchInput) return;
    
    const suggestions = ['龙舟', '剪纸', '茶艺', '粤剧', '木雕', '陶瓷'];
    
    // 焦点时显示建议
    searchInput.addEventListener('focus', function() {
        if (!this.value) {
            this.placeholder = `试试搜索：${suggestions[Math.floor(Math.random() * suggestions.length)]}`;
        }
    });
}

/**
 * 为卡片添加点击效果
 * @param {HTMLElement} card - 卡片元素
 */
function addCardClickEffect(card) {
    card.addEventListener('click', function() {
        const title = this.querySelector('h4')?.textContent || '非遗详情';
        showHeritageDetail(title);
    });
    
    // 添加悬浮效果
    card.addEventListener('mouseenter', function() {
        this.style.transform = 'translateY(-8px) scale(1.02)';
        this.style.boxShadow = '0 20px 40px rgba(0, 0, 0, 0.15)';
    });
    
    card.addEventListener('mouseleave', function() {
        this.style.transform = 'translateY(0) scale(1)';
        this.style.boxShadow = '0 8px 24px rgba(0, 0, 0, 0.1)';
    });
}

/**
 * 显示非遗详情弹窗
 * @param {string} title - 非遗项目标题
 */
function showHeritageDetail(title) {
    // 创建弹窗HTML
    const modalHTML = `
        <div class="heritage-modal" id="heritageModal">
            <div class="modal-content">
                <span class="close-modal">&times;</span>
                <h2>${title}</h2>
                <div class="modal-body">
                    <div class="heritage-detail-image">
                        <div class="image-placeholder">
                            <i class="fas fa-image"></i>
                            <p>非遗项目图片</p>
                        </div>
                    </div>
                    <div class="heritage-detail-info">
                        <h3>项目介绍</h3>
                        <p>这是一个珍贵的非物质文化遗产项目，承载着深厚的历史文化内涵和独特的艺术价值。</p>
                        
                        <h3>历史渊源</h3>
                        <p>该项目有着悠久的历史传承，体现了中华民族的智慧和创造力。</p>
                        
                        <h3>艺术特色</h3>
                        <p>具有鲜明的地方特色和独特的艺术表现形式。</p>
                        
                        <h3>传承现状</h3>
                        <p>目前正在积极保护和传承中，需要社会各界的关注和支持。</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary" onclick="closeHeritageModal()">关闭</button>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    // 显示弹窗
    const modal = document.getElementById('heritageModal');
    modal.style.display = 'flex';
    
    // 绑定关闭事件
    const closeBtn = modal.querySelector('.close-modal');
    closeBtn.addEventListener('click', closeHeritageModal);
    
    // 点击遮罩关闭
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeHeritageModal();
        }
    });
}

/**
 * 关闭非遗详情弹窗
 */
function closeHeritageModal() {
    const modal = document.getElementById('heritageModal');
    if (modal) {
        modal.remove();
    }
}

/**
 * 初始化知识卡片
 */
function initKnowledgeCards() {
    const knowledgeCards = document.querySelectorAll('.knowledge-card');
    
    knowledgeCards.forEach(card => {
        card.addEventListener('click', function() {
            const type = this.getAttribute('data-type') || 'general';
            showKnowledgeDetail(type);
        });
    });
}

/**
 * 显示知识详情
 * @param {string} type - 知识类型
 */
function showKnowledgeDetail(type) {
    let title = '非遗知识';
    let content = '非物质文化遗产知识内容...';
    
    switch(type) {
        case 'history':
            title = '非遗历史';
            content = '非物质文化遗产有着悠久的历史传承...';
            break;
        case 'protection':
            title = '非遗保护';
            content = '非物质文化遗产的保护工作非常重要...';
            break;
        case 'inheritance':
            title = '非遗传承';
            content = '非物质文化遗产的传承需要全社会的参与...';
            break;
        case 'innovation':
            title = '非遗创新';
            content = '在保护传统的同时，非遗也需要创新发展...';
            break;
    }
    
    showHeritageDetail(title);
}

// 为所有现有的非遗卡片添加点击效果
document.addEventListener('DOMContentLoaded', function() {
    if (document.body.classList.contains('theme-about')) {
        const existingCards = document.querySelectorAll('.heritage-card');
        existingCards.forEach(card => {
            addCardClickEffect(card);
        });
    }
});